

package com.hazelcast.internal.yaml;

import java.util.*;
import java.util.stream.Collectors;

import static com.hazelcast.internal.yaml.YamlUtil.*;

public class YamlMappingImpl extends AbstractYamlNode implements MutableYamlMapping {
    private Map<String, YamlNode> children = Collections.emptyMap();

    YamlMappingImpl(YamlNode parent, String nodeName) {
        super(parent, nodeName);
    }

    @Override
    public YamlNode child(String name) {
        return children.get(name);
    }

    @Override
    public YamlMapping childAsMapping(String name) {
        return asMapping(child(name));
    }

    @Override
    public YamlSequence childAsSequence(String name) {
        return asSequence(child(name));
    }

    @Override
    public YamlScalar childAsScalar(String name) {
        return asScalar(child(name));
    }

    @Override
    public <T> T childAsScalarValue(String name) {
        return childAsScalar(name).nodeValue();
    }

    @Override
    public <T> T childAsScalarValue(String name, Class<T> type) {
        return childAsScalar(name).nodeValue(type);
    }

    @Override
    public Iterable<YamlNode> children() {
        return children.values().stream().filter(Objects::nonNull).collect(Collectors.toList());
    }

    @Override
    public Iterable<YamlNameNodePair> childrenPairs() {
        List<YamlNameNodePair> pairs = new LinkedList<>();
        for (Map.Entry<String, YamlNode> child : children.entrySet()) {
            pairs.add(new YamlNameNodePair(child.getKey(), child.getValue()));
        }
        return pairs;
    }

    @Override
    public void addChild(String name, YamlNode node) {
        getOrCreateChildren().put(name, node);
    }

    @Override
    public void removeChild(String name) {
        children.remove(name);
    }

    private Map<String, YamlNode> getOrCreateChildren() {
        if (children == Collections.<String, YamlNode>emptyMap()) {
            children = new LinkedHashMap<>();
        }

        return children;
    }

    @Override
    public int childCount() {
        return children.size();
    }

    @Override
    public String toString() {
        return "YamlMappingImpl{" + "nodeName=" + nodeName() + ", children=" + children + '}';
    }

}
